package lx.scrmXj;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lx.util.DateUtil;
import lx.util.HttpHelper;

import java.text.MessageFormat;
import java.util.*;

/**
 * @Description: 成员消息发送
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/20 8:07
 */
public class MessageCustomerTask extends TimerTask {
    // 企业可通过此接口添加企业群发消息的任务并通知客服人员发送给相关客户或客户群
    // 调用该接口并不会直接发送消息给客户/客户群，需要相关的客服人员操作以后才会实际发送
    // 同一个企业每个自然月内仅可针对一个客户/客户群发送4条消息，超过限制的用户将会被忽略
    // 员工消息接口地址
    String message_customer_url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token={0}";
    String xj_scrm_message_customer_url = "SELECT * FROM XJ_SCRM_MESSAGE_CUSTOM WHERE BOOLEANSTATE = '0' AND STATE = 0 AND MSGTIME <= SYSDATE";

    @Override
    public void run() {
        List<Record> recordList = Db.find(xj_scrm_message_customer_url);
        try {
            System.out.println(MessageFormat.format("{0} 当前客户信息列表：{1}", DateUtil.dateToDateTimeCharacter(new Date()), recordList.size()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Record record : recordList) {
            messageCustomer(record);
        }
    }

    public void messageCustomer(Record record) {
        try {
            String msgtype = record.getStr("MSGTYPE"); // 消息类型
            String id = record.getStr("ID"); // 消息关联id
            String msgmsgid = "";//消息返回的msgid, 用作获取群发消息结果（员工消息的发送中暂时用不到）
            // 用户userid列表
            //String arrpeople = record.getStr("ARRPEOPLE"); // 成员的userid，多个以逗号分隔，格式：1，2，3
            //List<String> useridlist = Arrays.asList(arrpeople.split(","));
            String arrpeople = record.getStr("ARRPEOPLE"); // 成员的userid，多个以逗号分隔，格式：1，2，3
            List<String> useridlist = new ArrayList<>();
            if ("@all".equals(arrpeople)){
                List<Record> arrpeople_ = Db.find("SELECT USERID FROM XJ_SCRM_USER ");
                for (Record value : arrpeople_) {
                    useridlist.add(String.valueOf(value));
                }
            } else {
                useridlist = (Arrays.asList(arrpeople.split(",")));
            }

            // 客户消息json
            JSONObject customerJson = new JSONObject();
            //customerJson.put("agentid", "1000008"); // 企业应用id
            customerJson.put("chat_type", "single"); // TODO 群发任务的类型，默认为single，表示发送给客户，group表示发送给客户群
            if (msgtype.equals("1")) {  // TODO --------------------------------------------------------------------文本
                customerJson.put("msgtype", "text");
                JSONObject text = new JSONObject();
                text.put("content", record.getStr("marktext"));
                customerJson.put("text", text);
            } else if (msgtype.equals("2")) {  // TODO -------------------------------------------------------------图片
                customerJson.put("msgtype", "image");
                JSONObject image = new JSONObject();
                image.put("media_id", record.getStr("sucaiid"));
                customerJson.put("image", image);
            } else if (msgtype.equals("3")) {  // TODO -------------------------------------------------------------图文
                customerJson.put("msgtype", "news");
                JSONObject link = new JSONObject();
                link.put("title", record.getStr("marktext"));
                link.put("picurl", record.getStr("imgurl"));
                link.put("desc", record.getStr("msgtext"));
                link.put("url", record.getStr("imgtexturl"));
                customerJson.put("link", link);
            } else if (msgtype.equals("4")) { // TODO ------------------------------------------------------------小程序
                customerJson.put("msgtype", "miniprogram");

                JSONObject miniprogram = new JSONObject();
                miniprogram.put("title", record.getStr("smalltitle")); // 小程序消息标题，最多64个字节
                miniprogram.put("pic_media_id", record.getStr("sucaiid")); //  小程序消息封面的mediaid，封面图建议尺寸为520*416
                miniprogram.put("appid", record.getStr("smallappid")); // 小程序appid，必须是关联到企业的小程序应用
                miniprogram.put("page", record.getStr("smallpageurl")); // 小程序page路径

                customerJson.put("miniprogram", miniprogram);
            }

            for (int i = 0; i < useridlist.size(); i++) {
                String userid = useridlist.get(i); // 成员编号
                customerJson.put("sender", userid);
                try {
                    // 查询当前成员的客户信息列表
                    JSONArray external_userid_array = new JSONArray();
                    List<Record> customerList = Db.find("SELECT EXTERNAL_USERID FROM XJ_SCRM_CUSTOMER_MAINTAIN WHERE USERID = ?", userid);
                    for (int j = 0; j < customerList.size(); j++) {
                        String external_userid = customerList.get(j).getStr("EXTERNAL_USERID"); // 客户编号
                        external_userid_array.add(external_userid);
                    }
                    // TODO 客户的外部联系人id列表，仅在chat_type为single时有效，不可与sender同时为空，最多可传入1万个客户
                    customerJson.put("external_userid", external_userid_array); // 客户的外部联系人id列表，仅在chat_type为single时有效，不可与sender同时为空，最多可传入1万个客户
                    if (external_userid_array.size() == 0) {
                        continue;
                    }

                    int state = 0; // 发送状态( 0:未发送 1:已发送 2:发送失败)
                    String msgstate;// 发送结果
                    String res;

                    // 获取token，发送消息的必要条件
                    int category = 2;
                    if ("4".equals(msgtype)) {
                        category = 4;
                    }
                    String tokenUrl = "SELECT ACCESS_TOKEN FROM XJ_SCRM_TOKEN where CATEGORY = "+category+" ORDER BY CREATE_TIME DESC";
                    List<Record> recordTokenList = Db.find(tokenUrl);
                    if (recordTokenList.size() > 0) {
                        String token = recordTokenList.get(0).getStr("ACCESS_TOKEN");
                        System.out.println(MessageFormat.format("{0} TOKEN：{1}", DateUtil.dateToDateTimeCharacter(new Date()), token));
                        // 向当前成员的客户发送消息
                        System.out.println(MessageFormat.format("{0} 向成员（{1}）的客户发送消息入参报文：{2}", DateUtil.dateToDateTimeCharacter(new Date()), userid, customerJson));
                        res = HttpHelper.sendRequestHttps(MessageFormat.format(message_customer_url, token), "POST", customerJson);
                        System.out.println(MessageFormat.format("{0} 向成员（{1}）的客户发送消息出参报文：{2}", DateUtil.dateToDateTimeCharacter(new Date()), userid, res));
                        JSONObject respjson = JSONObject.parseObject(res);
                        if ("0".equals(respjson.getString("errcode"))) { // "errcode":0,"errmsg":"ok. Warning: wrong json format.
                            msgstate = "发送成功";
                            msgmsgid = respjson.getString("msgid"); // TODO 企业群发消息的id，可用于获取群发消息发送结果
                            state = 1;
                            System.out.println("客户消息发送结束，发送结果：" + msgstate + "," + state);
                        } else {
                            msgstate = "发送失败";
                            state = 2;
                        }
                        System.out.println(MessageFormat.format("向成语（{0}）的客户消息发送结束，发送结果：{1}", userid, msgstate + "," + state));
                    } else {
                        msgstate = "发送失败";
                        state = 2;
                        res = "从本地服务器获取TOKEN失败";
                    }
                    //
                    int updateState = Db.update("UPDATE XJ_SCRM_MESSAGE_CUSTOM SET STATE=? WHERE ID=?", state, id);
                    System.out.println("更新客户消息消息的发送状态结果：" + updateState);
                    //
                    Record insertRecord = new Record();
                    insertRecord.set("ID", UUID.randomUUID().toString());
                    insertRecord.set("MSGTYPE", msgtype);
                    insertRecord.set("MSGID", id);
                    insertRecord.set("REQ", customerJson.toString());
                    insertRecord.set("RESP", res);
                    insertRecord.set("MSGSTATE", msgstate);
                    insertRecord.set("MSGMSGID", msgmsgid);
                    boolean insertState = Db.save("XJ_SCRM_MESSAGE_RESP", "ID", insertRecord);
                    System.out.println("添加客户消息发送记录结果：" + insertState);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(MessageFormat.format("向成员（{0}）的客户消息发送出错：{1}", userid, e.getMessage()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("客户消息发送出错：" + e.getMessage());
        }

    }

}
